package com.browsesoft.util;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.browsesoft.htmlcomponent.HTMLPage;
import com.browsesoft.htmlcomponent.Window;

/**
 * HttpSession工具类
 */
public class SessionHelper {

	/**
	 * 从Session中根据页面名得窗口
	 */
	public static Window getWindow(HttpSession session, String name) {
		Window window = (Window) session.getAttribute(name);
		if (window != null) {
			return window;
		}
		window = new Window();
		session.setAttribute(name, window);
		return window;
	}

	/**
	 * 从Session中根据页面名得页面
	 */
	public static HTMLPage getPage(HttpSession session, String name) {
		HTMLPage page = (HTMLPage) session.getAttribute(name);
		if (page != null) {
			return page;
		}
		Enumeration en = session.getAttributeNames();
		while (en.hasMoreElements()) {
			String pname = (String) en.nextElement();
			Object obj = session.getAttribute(pname);
			// 如果不是Window，继续查找
			if (!(obj instanceof Window)) {
				continue;
			}
			// 如果是Window，在Window内找到需要的页面
			Window w = (Window) obj;
			page = w.getPage();
			String p = page.getName();
			if (p.equals(name)) {
				return page;
			}
		}
		return null;
	}

	/**
	 * 根据请求把页面放到Session中
	 */
	public static void putPage(HttpServletRequest request, HTMLPage page) {
		HttpSession session = request.getSession();
		String window = request.getParameter("window");
		// 如果请求里有window则把页面放入window,否则把页面放入session中
		if (window != null && window.equals("")) {
			SessionHelper.getWindow(session, window).setPage(page);
		} else {
			session.setAttribute(page.getName(), page);
		}
	}
}
